<template>
  <div>
    <el-card>
      <el-table :data="classifyList1" style="width: 90%" :row-key="rowKey" border lazy :load="load"
        :tree-props="{ children: 'children', hasChildren: 'grade' }" :row-class-name="rowStyle">
        <el-table-column label="分类ID" width="100" prop="id" align="center">
        </el-table-column>
        <el-table-column prop="name" label="分类名">
        </el-table-column>
        <el-table-column prop="address" width="180">
          <template slot="header" slot-scope="{ column, $index }">
            <el-input placeholder="按下回车键搜索分类" size="mini" clearable></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import categoryApi from '@/api/category'
import { mapState } from 'vuex'

export default {
  name: 'Classify',
  data() {
    return {
    }
  },
  methods: {
    async load(tree, treeNode, resolve) {
      // 如果当前是一级分类列表
      if (tree.grade === 1) {
        await this.$store.dispatch('getCategory2', tree.id)
        const arr = this.csList2
        arr.forEach(item => item.grade = 2)
        resolve(arr)
      } else if (tree.grade === 2) {
        await this.$store.dispatch('getCategory3', tree.id)
        const arr = this.csList3
        resolve(arr)
      }
    },
    // 获取一级分类
    async getclassfiy1() {
      await this.$store.dispatch('getCategory1')
    },
    // 获取row
    rowKey(row) {
      // console.log(row);
      return row.id + '&' + row.grade
    },
    // 添加样式
    rowStyle({ row, rowIndex }) {
      if (row.grade === 2) {
        return 'twoStyle'
      } else {
        return ''
      }
    }
  },
  mounted() {
    this.getclassfiy1()
  },
  computed: {
    ...mapState({
      csList1: state => state.headercategory.category1List,
      csList2: state => state.headercategory.category2List,
      csList3: state => state.headercategory.category3List,
    }),
    // 使用一级分类计算出一个新的数据，因为我们的row-key需要不重复的数据
    classifyList1() {
      return this.csList1.map((item, index) => {
        return {
          id: item.id,
          name: item.name,
          grade: 1
        }
      })
    }
  }
}
</script>

<style scoped>
::v-deep .el-table .twoStyle {
  background-color: rgba(144, 238, 144, 0.507) !important;
}
</style>
